<template>
    <div class="content">
        <div class="header">
            <p class="title">添加病历信息</p>
        </div>
        <div class="patient-info">
            <table class="patient-data" >
               <tr class="first_line">
                    <td class="key" >姓名</td>
                    <td style="position: relative;" colspan="4"  @focus="">
                        <input autocomplete="off" class="value" id="name" @focus="show_select_list=true" @blur="td_change1($event),mouse_leave?show_select_list=false:0"   v-model.trim="patient.name" style="width:100%;border:none" type="text" />
                        <!-- <input list="select_list" class="value" id="name" v-model="patient.name" style="width:100%;border:none" type="text" /> -->
                        <!-- <datalist @click="select_pient" id="select_list">
                            <option :card_id="item.card_id"  v-for="(item,index) in select_lista" :value="`${item.name}`">{{ item.card_id }}</option>
                        </datalist> -->
                        <!-- 选择列表 -->
                        <div class="select_list" v-show="show_select_list" @mouseenter="mouse_leave=false" @mouseleave="mouse_leave=true" >
                            <li @click="select_patient(item,index)" v-for="(item,index) in select_list" v-show="select_list">{{item.name+" "+item.card_id}}</li>
                        </div>
                    </td>
                    
                    <td class="key">出生年日</td><td colspan="3" class="value" id="birthday" @blur="td_change1($event)">{{ patient.birthday }}</td><td colspan="1" style="fontSize:10px" v-show="patient.age">年龄：{{ patient.age }}</td>
                </tr>
                <tr>
                    <td class="key">身份证号</td><td colspan="4" class="value" id="card_id" @blur="td_change1($event)">{{ patient.card_id }}</td>
                    <td class="key">手机号码</td><td colspan="4" class="value" id="phone" @blur="td_change1($event)">{{ patient.phone }}</td>
                </tr>
                <tr>
                    <td class="key">最近看病时间</td><td colspan="4" class="value" id="last_time" @blur="td_change1($event)">{{ patient.last_time }}</td>
                    <td class="key">医保类别</td><td colspan="4" class="value" id="medical_insurance" @blur="td_change1($event)">{{ patient.medical_insurance }}</td>
                </tr>
                <tr>
                    <td class="key">目前身体状况</td><td colspan="4" class="value" id="health" @blur="td_change1($event)">{{ patient.health }}</td>
                    <td class="key">性别</td><td colspan="4" class="value" id="gender" @blur="td_change1($event)">{{ patient.gender }}</td>
                </tr>
                <tr>
                    <td colspan="10" style="fontWeight:bolder" >病历</td>
                </tr>
                <tr v-for="(meide_r,index) in patient.medical_record" :key="index" @click="current_medical_record(meide_r,index)" :class="{select:index==select_medical_record}">
                    <!-- <td colspan="1" class="key value" @blur="td_change($event,index,1)" id="treat_time">{{ meide_r["treat_time"] }}</td> -->
                    <td class="first_col">
                        <tr>
                            <td colspan="2" class="key value" @blur="td_change($event,index)" id="treat_time">{{ meide_r["treat_time"] }}</td>
                        </tr>
                        <tr>
                            <td style="fontWeight: bolder;">病历号</td><td id="id">{{ meide_r.id }}</td>
                        </tr>
                    </td>
                    
                    <td class="medical_record" colspan="9">
                        <tr>
                            <td style="fontWeight: bolder;">就诊医院:</td><td small id="treat_hospital" class="value" @blur="td_change($event,index)"> {{ meide_r["treat_hospital"] }} </td>
                            <td style="fontWeight: bolder;">症状:</td><td id="symptom_description" colspan="2" class="value" @blur="td_change($event,index)"> {{ meide_r["symptom_description"] }} </td>
                        </tr>
                        <tr>
                            <td style="fontWeight: bolder;">就诊医生:</td><td small id="docter_name" class="value" @blur="td_change($event,index)">{{ meide_r["docter_name"] }}</td>
                            <td style="fontWeight: bolder;">处方:</td><td id="prescription" colspan="2" class="value" @blur="td_change($event,index)">{{ meide_r["prescription"] }}</td>
                        </tr>
                        <tr>
                            <td style="fontWeight: bolder;">治疗结果:</td><td small id="treatment_results" class="value" @blur="td_change($event,index)">{{ meide_r["treatment_results"] }}</td>
                            <td style="fontWeight: bolder;">用药:</td><td id="use_medicinal" colspan="2" class="value" @blur="td_change($event,index)">{{ meide_r["use_medicinal"] }}</td>
                        </tr>
                    </td>
                </tr>
            </table>
            
            
            <!-- <p v-else class="spare">请输入你要查询的信息</p> -->
            <div class="button" v-if="patient">
                <button class="edit" @click="edit($event)">{{ button_text }}</button>
                <!-- <button v-show="submitShow" class="add_medical_record" @click="add_medical_record">新增病历</button> -->
                <!-- <button v-show="submitShow" class="add_medical_record" @click="del_medical_record">删除病历</button> -->
                <button v-show="submitShow" class="add_medical_record" @click="reset">重置</button>
                <button v-show="submitShow" class="submit" @click="submit">提交</button>
                <!-- <button class="back_list" @click="$router.push('/medical_record_list')">返回列表</button> -->
            </div>
        </div>
    </div>
</template>

<script>

export default {
    name:'add_medical_record',
    data(){
        return {
            submitShow:false,
            button_text:'编辑信息',
            select_medical_record:null,
            select_medical_record_item:null,
            patient_list:null,
            patient:{
                id:"null",
                name:"",
                birthday:"",
                card_id:"",
                phone:"",
                last_time:"",
                register_n:"",
                health:"",
                medical_record:[],
                treat_record:[]
            },
            old_patient:{},
            new_patient:{},
            del_m_r:[],
            err_msg:"",
            err_msg_show:false,
            select_list:[],
            show_select_list:false,
            mouse_leave:false,
        }
    },
    methods:{
        edit(e){
            let el = document.querySelectorAll(".value")
            if(this.button_text=='编辑信息'){
                this.button_text='取消'
                this.submitShow=!this.submitShow
                el.forEach(item=>{
                    item.setAttribute("contentEditable",this.submitShow)
                })
                el[0].focus()
            }else{
                window.close()
                this.button_text='编辑信息'
                this.submitShow=!this.submitShow
                this.update_patient()
                el.forEach(item=>{
                    item.setAttribute("contentEditable",this.submitShow)
                })
            }
        },
        reset(){
            this.patient={
                id:"null",
                name:"",
                birthday:"",
                card_id:"",
                phone:"",
                last_time:"",
                register_n:"",
                health:"",
                medical_record:[],
                treat_record:[]
            }
            this.add_medical_record()
            this.old_patient={}
            this.select_list=[]
        },
        add_medical_record(){  // 添加病历
            let time = new Date().toLocaleDateString()  // .replace(/\//g,"-")
            this.patient.medical_record.push({
                "id":"null",
                "patient_id":this.patient["id"],
                "patient_name":this.patient["name"],
                "patient_gender":this.patient["gender"],
                "medical_insurance":this.patient["medical_insurance"],
                "treat_time":time,
                "treat_hospital":"重庆XX医院",
                "docter_name":"",
                "symptom_description":"",
                "prescription":"",
                "use_medicinal":"",
                "treatment_results":""
            })
            setTimeout(()=>{
                let el = document.querySelectorAll(".value")
                el.forEach(item=>{
                    item.setAttribute("contentEditable",this.submitShow)
                })
            })
        },
        del_medical_record(){  // 删除病历
            if(this.select_medical_record==null){
                this.$toast.fail("请先点击要删除的病历")
                return
            }
            let conf = confirm("你确定要删除该信息吗")
            if(!conf){
                console.log("取消编辑");
                return
            }
            let m_id = this.patient.medical_record[this.select_medical_record]["id"]
            let patient_id = this.patient.medical_record[this.select_medical_record]["patient_id"]
            if( m_id != "null"){
                let temp={}
                temp["id"]=m_id
                temp["patient_id"]=patient_id
                temp["table_name"]="medecal_record"
                this.del_m_r.push(temp)
            }
            this.patient.medical_record.splice(this.select_medical_record,1)
            // this.new_patient.medical_record.splice(this.select_medical_record,1)
            this.select_medical_record=null
            // setTimeout(()=>{
            //     let el = document.querySelectorAll(".value")
            //     el.forEach(item=>{
            //         item.setAttribute("contentEditable",this.submitShow)
            //     })
            // })
            console.log(this.del_m_r);
        },
        current_medical_record(item,index){  // 记录当前选择的病历
            this.select_medical_record_item = item
            this.select_medical_record = index
        },
        select_patient(item,index){  // 选择已存在的病人后执行的操作
            this.patient=this.select_list[index]
            this.show_select_list=false
            if(this.patient.medical_record.length<1){
                this.add_medical_record()
            }
            this.old_patient.name=this.patient.name
            this.old_patient.card_id=this.patient.card_id
        },
        td_change(el,index){  // 输入病历信息后，保存病历信息
            // if(num==0){
            //     this.patient.medical_record[index][0](0,1,el.currentTarget.innerText.trim())
            //     let e = el.currentTarget
            //     let id = e.getAttribute("id")
            //     this.patient.medical_record[index][id]=e.innerText.trim()
            // }else if(num==1){
            let e = el.currentTarget
            let id = e.getAttribute("id")
            this.patient.medical_record[index][id]=e.innerText.trim()
            // }
        },
        td_change1(e){  // 保存基本资料
            let el = e.currentTarget
            let id = e.currentTarget.getAttribute("id")
            this.patient[id]=el.innerText.trim()
            if(id=="name"){
                this.patient[id]=el.value.trim()
            }
        },
        td_change2(){
            console.log("内容发生改变");
        },
        check_data(data){  // 检查输入的信息是否正确
            
            for (let item in data){
                if (data[item] instanceof Array){
                    let temp = data[item]
                    for(let i in temp){
                        let ret = this.check_data(temp[i])
                        if(ret==false){
                            return false
                        }
                    }
                }
                if(this.$my_tools.check_data[item]){ 
                    
                    let msg=this.$my_tools.check_data[item](data[item])
                    if(msg){
                        this.$toast(msg)
                        this.err_msg=msg
                        this.err_msg_show=true
                        return false
                    }
                }
            }
        },
        submit(){  // 提交编辑后的信息
            if(this.check_data(this.patient)==false){
                return
            }
            // document.querySelectorAll(".edit")[0].innerText="编辑信息"
            // this.submitShow=false
            let conf = confirm("你确定要保存该编辑吗")
            if(!conf){
                this.$toast("您已取消操作")
                return
            }

            if (this.old_patient.name && (this.patient.name != this.old_patient.name || this.patient.card_id != this.old_patient.card_id)){
                
                if(this.patient.card_id == this.old_patient.card_id){
                    conf = confirm("新的【姓名】 与 原来的姓名 不一样\n是要修改之前的病人信息吗？")
                    if(!conf){
                        this.$toast("您已取消操作")
                        return
                    }
                }else{
                    conf = confirm("新的【姓名】 或者 【身份证】 信息与原来的不一样\n是要重新创建新的病人信息吗？")
                    if(conf){
                        this.patient.id="null"
                    }else{
                        this.$toast("您已取消操作")
                        return
                    }
                }
            }

            this.button_text='编辑信息'
            this.submitShow=!this.submitShow
            let values = document.querySelectorAll(".value")
            values.forEach((item,index)=>{
                item.setAttribute("contentEditable",this.submitShow)
            })
            // 为了保险起见，还是验证下删除列表del_m_r里的病历 是否是当前病人的病历，这一步貌似可以省略
            if(this.del_m_r.length>0){  
                this.del_m_r.forEach((item,index)=>{
                    if(item.patient_id != this.patient.id){
                        this.$toast.fail("你要删除的病历不是当前病人的，请重新刷新页面试试")
                        return
                    }
                })
            }
            // 发送ajax请求，保存数据
            console.log(this.patient,"提交");
            this.$http({
                method:'post',
                url:'/ajax/api/add_medical_record',
                data:{
                    patient:this.patient
                }
            }).then(data=>{
                if(data.data=="ok"){
                    this.$toast.success("操作成功,5秒后关闭窗口")
                    this.$router.push("/")
                    // let timer=3
                    // setInterval(() => {
                    //     timer--
                        
                    // }, 1000);
                    setTimeout(() => {
                        window.close()
                    }, 5000);
                    
                    // this.$http({
                    //     method:'post',
                    //     url:'/ajax/api/search_patient',
                    //     data:{
                    //         patient:{name:this.patient.name}
                    //     }
                    // }).then(data=>{
                    //     this.$store.state.patient = data.data
                    //     this.patient=this.$my_tools.deepClone(this.$store.state.patient[0])
                    //     // if(this.$route.path=="/add_patient"){
                    //     //     this.$router.push("/patientInfo")
                    //     // }
                    // })

                }else{
                    this.$toast.fail("编辑失败，发生未知错误")
                }
            })
            // this.$toast("添加成功")
            // this.$router.push('/')
            this.$store.state.patient[0]=this.$my_tools.deepClone(this.patient)
        },
        update_patient(){
            this.params_id = this.$route.params.id
            this.drugs_details=this.$my_tools.deepClone(this.$store.state.drugs_list[this.params_id])
            console.log(this.drugs_details);
            // this.patient =this.$my_tools.deepClone(this.$store.state.patient[0])
            // this.del_m_r=[]  // 当重新查询数据的时候，初始化删除列表del_m_r
            // console.log(this.patient);
        },
    },
    watch:{
        'patient.name':function(val,oldval){
            this.$http({
                method:'post',
                url:'/ajax/api/search_patient',
                data:{
                    patient:{name:this.patient.name},
                    only_search_patient:true
                }
            }).then(data=>{
                this.select_list=data.data.patient_list
                console.log(this.select_list);
            })
        }
    },
    mounted(){
        // this.params_id = this.$route.params.id
        // if(this.$store.state.drugs_list){
        //     this.drugs_details=this.$my_tools.deepClone(this.$store.state.drugs_list[this.params_id])
        // }
        this.edit()
        this.add_medical_record()
    }
}
</script>

<style lang='scss' scoped>
.content{
    margin: 5px;
    overflow: auto;
    height: 100%;
    .title{
        font-weight: bolder;
        margin:10px 0;
        text-align: center;
    }
    .patient-info{
        border: 1px solid #ccc;
        // width: 90%;
        height: 100%;
        margin-top: 5px;
        padding: 5px;
        overflow: auto;
        display: flex;
        align-items: flex-start;
        // position: relative;
        // 表格样式
        table{
            flex:0 0 auto;
            border: 1px solid #aaa;
            .first_line{
                overflow: hidden;
                input{
                    width: 100%;
                    // margin: -20px;
                }
            }
            input::-webkit-calendar-picker-indicator{
                opacity: 0;
            }
            
            td{
                border: 1px solid #aaa;
                padding: 8px;
                vertical-align: middle;
            }
            .value{
                width: 200px;
                word-break: break-all;
            }
            .key{
                font-weight: bolder;
                width: 100px;
            }

            .medical_record{
                padding: 3px;
                td{
                    // padding: 10px;
                    border:none;
                    font-size: 13px;
                }
                .value{
                    border-bottom: 1px solid #aaa;
                    width:300px;
                }
                [small]{
                    width: 130px;
                }
                
            }
            .first_col td{
                border: none;
            }
        }

        .select_list{
            position:absolute;
            list-style: none;
            top:100%+10;
            // left:10px;
            // margin: 10px;
            width: 100%-10;
            z-index: 2;
            background-color:rgb(253, 241, 241);
            // border: 1px solid black;
            li{
                // font-size: 16px;
                color:#555;
                margin:5px 0px;
                // line-height: 16px;
            }
            li:hover{
                color:#333;
                font-weight: bolder;
                cursor:default;
            }
        }

        .button{
            display: flex;
            margin-left: 10px;
            flex-direction: column;
            button{
                margin-bottom: 10px;
                width: 80px;
                // text-align:ce;
                // background-color: rgb(245, 159, 102);
                // color: rgb(247, 238, 201);
            }
        }
        // .center{
        //     font-weight: bolder;
        //     // text-align: center;
        // }
        // .spare{
        //     font-size: 20px;
        //     font-weight: bolder;
        //     margin: 50px auto;
        // }
        .select{
            background-color: #f1f1f1;
        }
        
    }
    

}
</style>